﻿use sms
go
if exists(select name from sysobjects where name ='cp_mark_sendfailed' and type = 'P')
drop procedure cp_mark_sendfailed
go 
/****** Object:  StoredProcedure [dbo].[cp_mark_sendfailed]    Script Date: 12/01/2010 14:56:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
----发送失败时调用
CREATE procedure [dbo].[cp_mark_sendfailed]
@id int --发送失败的ID，更改状态
as
declare @state int
--查询传入ID的Message当前State
select @state = [State] from [Message] where ID = @id
--根据State判断
--正在发送
if(@state & 0xf0 = 0x10)
	begin
		--改为待发送，修改重发次数++（State）
		update [Message] set [State] = (@state & 0x0f) + 1,ModifyTime = GETDATE() where ID = @id
	end
--待发送
else if(@state & 0xf0 = 0x00)
	begin
		--为待发送，判断已发次数是否小于最大发送次数
		--当前已重发次数,最大发送次数
		declare @reRetry int, @maxRetry int 
		--获得当前重发次数和重发上限次数
		select @reRetry = [State] & 0x0f , @maxRetry = MaxRetryTime from [Message] where ID=@id  
		----当前已重发次数>最大发送次数时
		print  @reRetry
		print  @maxRetry
		if(@reRetry >= @maxRetry)
			begin
			print @state
				--把短信状态设置为发送失败
				update [Message] set [State] = (@state | 0x20),ModifyTime = GETDATE()  where ID = @id
				--再查找同一批次的短信状态是否一致
				declare @counts int, @batchid int
				select @batchid = [BatchID] from [Message] where ID=@id
				select @counts = COUNT(*) from [Message] where BatchID = @batchid
				--state = '正在发送' or state = '待发送'
				and ([State] & 0xf0 = 0x10 or [State] & 0xf0 = 0x00)
				--如果为0则返回同一批次(BatchID)的记录
				if(@counts = 0)
					begin
						select * from [message] where BatchID = @batchid
					end
				else
					begin
						select * from [message] where ID = -1
					end
			end
		else
			begin
				--重发次数++
				update [Message] set [State] = @state+1,ModifyTime = GETDATE() where ID = @id
				--返回为空的table
				select * from [message] where ID = -1
			end			
	end
